<template>
    总数：{{ state.rawData.length }}
    数量：{{ state.data.length }}
    <el-row>
        <div :style="`width: ${state.width};`">
        <el-table :data="state.data" height="900"
        :cell-class-name="tableCellClassName"
        @sort-change="sortChange"
        @cell-click="cellClick"
        :default-sort="state.sort"
        :summary-method="summaryMethod"
        show-summary >
            <el-table-column prop="date" label="date" width="120" sortable fixed/>
            <el-table-column prop="day" label="星期" width="80">
                <template #default="scope">
                    {{ getDayOfWeek(scope.row.date) }}
                </template> 
            </el-table-column>
            <el-table-column prop="time" label="时间" width="100" />
            <el-table-column v-if="!stock" prop="stock" label="股票" width="130" />
            <el-table-column prop="display" label="diaplay" width="100" sortable>
                <template #default="scope"> 
                    <to-d-display :stock="scope.row.stock" :date="scope.row.date" />
                </template>
            </el-table-column>
            <el-table-column prop="drawdown" label="drawdown" width="100" sortable/>
            <el-table-column prop="curPct" label="curPct" width="100" sortable/>
            <el-table-column prop="optCurPct" label="optCurPct" width="100" sortable/>
            <el-table-column prop="operation" label="operation" width="100"/>
            <el-table-column prop="pct" label="pct"/>
            <el-table-column prop="desc" label="desc"/>
            <el-table-column prop="levelPoint" label="分位点"/>
            <el-table-column v-if="!stock" prop="d10MinPct" label="10minPct"/>
            <el-table-column v-if="!stock" prop="d10MaxPct" label="10maxPct" sortable/>
            <el-table-column prop="operateNum" label="手数"/>
            <el-table-column prop="price" label="价格" width="100" sortable/>
            <el-table-column prop="amount" label="总金额" width="120" sortable/>
            <el-table-column prop="indicator" label="指标" width="100" show-overflow-tooltip/>
            <el-table-column prop="reason" label="原因" width="160" show-overflow-tooltip/>
            <el-table-column prop="nextOperate" label="后续操作" width="200" show-overflow-tooltip/>
            <el-table-column v-if="!stock" prop="extra" label="补充说明" width="200" show-overflow-tooltip/>
        </el-table>
        </div>
    </el-row>
</template>

<script setup>
import { reactive } from 'vue';
import { getSessionStorage, setSessionStorage } from '@/utils/help';
import { getLpClassName } from '@/utils/help';
import { getLastedOperation } from '@/service/operation';
import { calScreenWidth, getDayOfWeek } from '../../utils/help';
import ToDDisplay from '../element/ToDDisplay.vue';
import { useRouteQuery } from '../../utils/useRoute';

const baseKey = "LastedOperation"
const selectKey = baseKey + "Select"
const sortPropKey = baseKey + "SortProp"
const sortOrderKey = baseKey + "SortOrder"

const props = defineProps({
    stock: String
})

const state = reactive({
    width : "1000px",
    rawData: [],
    data: [],
    operationSelected: "",
    operationSelectedStock: "",
    selected: getSessionStorage(selectKey) || '全部',
    sort: { 
        prop: getSessionStorage(sortPropKey) || 'date' , 
        order: getSessionStorage(sortOrderKey) || 'desc' 
    }
})

state.width = calScreenWidth()

if (props.stock) {
    state.operationSelectedStock = props.stock
}

let page = useRouteQuery('p',1)
let pageSize = useRouteQuery('ps',250)

const loadData = () => {
    getLastedOperation(state.operationSelectedStock).then( res => {
        state.rawData = res.data
        if (state.operationSelectedStock) {
            state.data = state.rawData
        } else {
            state.data = state.rawData.slice((page - 1) * pageSize, page * pageSize)
        }
    })
}
        
loadData()

const sortChange = (column, prop, order) => {
    setSessionStorage(sortPropKey, column.prop)
    setSessionStorage(sortOrderKey, column.order)
}

const cellClick = (row, column, cell, event) => {
    let columnProperty = column.property
    let val = row[columnProperty]

    if (columnProperty == 'stock') {
        // 点相同的股票名则取消选择
        if (state.operationSelectedStock != "" && state.operationSelectedStock == val) {
            state.operationSelectedStock = ""
        } else {
            state.operationSelectedStock = val
        }
        // 重新请求数据
        loadData()
    }

    if (['operation','date','indicator','desc'].includes(columnProperty)) {
        if (state.operationSelected != "" && state.operationSelected == val) {
            state.operationSelected = ""
            if (state.operationSelectedStock) {
                state.data = state.rawData
            } else {
                state.data = state.rawData.slice((page - 1) * pageSize, page * pageSize)
            }
        } else {
            state.operationSelected = val
            state.data = state.rawData.filter(item => item[columnProperty] == val)
        }
    }
}


const tableCellClassName = ({row, column, rowIndex, columnIndex}) => {
    var columnProperty = column.property
    var v = row[columnProperty]

    if (columnProperty == 'operation') {
        if (v == "卖出") {
            return 'lt0-cell';
        } else if ( v == '买入') {
            return 'wugu-lt100-cell'
        } else if ( v == '分红') {
            return 'lpgt99-cell'
        } else if ( v == '模拟买入') {
            return 'lplt10-cell'
        } else if ( v == '模拟卖出') {
            return 'wugu-gt1000-cell'
        }
    }
    if (columnProperty == 'levelPoint') {
        if (v) {
            return getLpClassName(v)
        }
    }
    if (['curPct','optCurPct','pct','d10MaxPct'].includes(columnProperty)) {
        if (v < 0) {
            return 'lt0-cell'
        }
    }

    if (columnProperty == 'drawdown') {
        if (v == 0) {
            return 'wugu-lt100-cell'
        }
    }
    return ''
}

const summaryMethod = (param) => { 
    const { columns, data } = param;
    const sums = [];

    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '汇总：';
            return;
        }

        if (["amount","operateNum"].includes(column.property)) {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
                const validValues = values.filter(value => !isNaN(value));
                if (validValues.length > 0) {
                    const sum = validValues.reduce((prev, curr) => prev + curr, 0);
                    sums[index] = `${sum.toFixed(2)}`;
                }
            }
        }
    })

    return sums;
}
</script>

<style>
</style>